<template>
  <div class="ma-content-block flex p-4">
    <div class="h-full shadow w-60">
      <ma-tree-slider
        v-model:visible="formVisible"
        :data="depts"
        searchPlaceholder="大屏分类"
        v-model="defaultKey"
        @click="switchDept"
        is-edit
        is-title
      >
        <template #title="{ nodeData }">
          {{ nodeData.label }}
          {{ nodeData.visual_count ? `(${nodeData.visual_count})` : "" }}
        </template>
        <template #edit>
          <ma-form v-model="form" :columns="formColumns" ref="crudForm" @submit="handlerSubmit" />
        </template>
        <template #editData="nodeData">
          <div class="opacity-100 hover:opacity-100 flex gap-1">
            <a-button @click="formEdit(nodeData)" type="text" class="text-right p-1">
              <i class="bi-edit-line" />
            </a-button>
            <a-popconfirm content="确定删除?" @ok="formDel(nodeData)">
              <a-button status="danger" type="text" class="text-right p-1">
                <i class="bi-delete-bin-2-line" />
              </a-button>
            </a-popconfirm>
          </div>
        </template>
      </ma-tree-slider>
    </div>
    <div class="lg:ml-4 flex-1 w-70">
      <!-- CRUD 组件 -->
      <ma-crud :options="crud" :columns="columns" ref="crudRef">
        <template #crudContent="tableData">
          <a-grid
            :cols="{ xs: 1, sm: 2, md: 3, lg: 3, xl: 4, xxl: 5 }"
            :colGap="12"
            :rowGap="16"
            :body-style="`padding:0`"
            hoverable
          >
            <a-grid-item v-for="item in tableData" :key="item.id">
              <a-card hoverable>
                <template #cover>
                  <a-image
                    class="w-full"
                    :title="item.title"
                    width="100%"
                    :height="128"
                    :src="$url + item.background_url"
                    footer-class="backdrop-blur h-8"
                  />
                  <div
                    class="absolute -top-0 w-full h-[128px] backdrop-blur-sm opacity-0 hover:opacity-100 flex items-center justify-center gap-3"
                  >
                    <a-button size="small" type="primary" @click="goEdit(item)">
                      <icon-computer />
                      设计
                    </a-button>
                    <a-button size="small" status="success" type="primary" @click="goPrview(item)">
                      <icon-eye />
                      预览
                    </a-button>
                  </div>
                </template>
                <a-card-meta :title="item.title" class="text-right">
                  <template #title>
                    <a-link class="text-black" v-auth="crud.edit.auth" @click="edit(item)">
                      <icon-edit />
                      编辑
                    </a-link>
                    <a-link class="text-black" @click="goEdit(item)">
                      <icon-copy />
                      复制
                    </a-link>
                    <a-popconfirm content="确定删除?" @ok="del(item)">
                      <a-link class="text-black" v-auth="crud.delete.auth">
                        <icon-delete />
                        删除
                      </a-link>
                    </a-popconfirm>
                  </template>
                </a-card-meta>
              </a-card>
            </a-grid-item>
          </a-grid>
        </template>
        <template #tableBeforeButtons>
          <a-button @click="goEdit(0)"> 新建大屏</a-button>
        </template>
      </ma-crud>
    </div>
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, onMounted } from "vue"
import api from "../api/visual"
const crudRef = ref()
const crud = reactive({
  api: api.getPageList,
  recycleApi: api.getRecyclePageList,
  searchColNumber: 3,
  pageSimple: true,
  showSearch: false,
  pageSize: 20,
  requestParams: {},
  showIndex: false,
  pageLayout: "fixed",
  isExpand: false,
  rowSelection: undefined,
  operationColumn: true,
  operationColumnWidth: 140,
  // add: { show: true, api: api.save, auth: ["/visual/Visual/save"] },
  edit: { show: true, api: api.update, auth: ["/visual/Visual/update"] },
  delete: {
    show: true,
    api: api.delete,
    auth: ["/visual/Visual/destroy"],
    realApi: api.realDestroy,
    realAuth: ["/visual/Visual/realDestroy"]
  }
})

const columns = reactive([
  {
    title: "主键",
    dataIndex: "id",
    width: 180,
    search: false,
    addDisplay: false,
    editDisplay: false,
    hide: true,
    formType: "input",
    commonRules: [{ required: true, message: "主键必填" }]
  },
  {
    title: "大屏标题",
    dataIndex: "title",
    width: 180,
    search: true,
    addDisplay: true,
    editDisplay: true,
    hide: false,
    formType: "input",
    commonRules: [{ required: false, message: "大屏标题必填" }]
  },
  {
    title: "大屏背景",
    dataIndex: "background_url",
    width: 180,
    search: false,
    addDisplay: true,
    editDisplay: true,
    formType: "upload",
    type: "image",
    commonRules: [{ required: false, message: "大屏背景必填" }],
    customRender: ({ record }) => {
      return <a-image src={record.background_url} width="152" height="78" fit="fill" />
    }
  },
  {
    title: "大屏分类",
    dataIndex: "cid",
    width: 180,
    search: false,
    addDisplay: true,
    editDisplay: true,
    hide: false,
    formType: "tree-select",
    multiple: false,
    dict: { url: "/visual/category/index?tree=true" },
    commonRules: [{ required: false, message: "大屏分类必填" }],
    customRender: ({ record }) => {
      return record?.category?.title
    }
  }
])
import { useRouter } from "vue-router"
import MaTreeSlider from "@cps/ma-treeSlider/index.vue"
import { Message } from "@arco-design/web-vue"
const router = useRouter()
const edit = (record) => {
  console.log(crudRef.value.crudFormRef.edit(record))
}

const goEdit = (record) => {
  const route = router.resolve({
    path: "/visualEditor",
    query: { id: record.id, name: record.name }
  })
  window.open(route.href, "_blank")
}

const goPrview = (record) => {
  const route = router.resolve({
    path: "/visual/preview",
    query: { id: record.id, name: record.name }
  })
  window.open(route.href, "_blank")
}

const del = async (record) => {
  const response = await crud.delete.api({ ids: [record.id] })
  response.code === 200 && Message.success(response.message || `删除成功！`)
  crudRef.value.requestData()
}

import visualCategory from "../api/visualCategory.js"
const depts = ref([{ label: "所有分类", value: 0 }])
onMounted(() => {
  visualCategory.tree().then((res) => {
    depts.value.push(...res.data)
  })
})
const defaultKey = ref([0])
const switchDept = (id) => {
  crudRef.value.requestParams = id[0] === 0 ? { cid: undefined } : { cid: id[0] }
  crudRef.value.requestData()
  defaultKey.value = id
}
const form = ref({})
const formVisible = ref(false)
// 组件的字段设置
const formColumns = reactive([
  {
    title: "上级分类",
    dataIndex: "pid",
    width: 180,
    search: false,
    addDisplay: true,
    editDisplay: true,
    hide: false,
    formType: "tree-select",
    multiple: false,
    dict: { url: "/visual/category/index?tree=true" },
    commonRules: [{ required: false, message: "分类必填" }],
    customRender: ({ record }) => {
      return record?.category?.title
    }
  },
  {
    title: "分类名称",
    dataIndex: "title",
    width: 180,
    search: false,
    addDisplay: true,
    editDisplay: true,
    hide: false,
    formType: "input",
    rules: [{ required: true, message: "分类名称必填" }]
  },
  {
    title: "排序",
    dataIndex: "sort",
    width: 180,
    search: false,
    addDisplay: true,
    editDisplay: true,
    hide: false,
    formType: "input",
    rules: [{ required: true, message: "分类名称必填" }]
  }
])

const handlerSubmit = (data, done) => {
  // 显示表单提交中状态
  done(true)
  if (data) {
    let url = ""
    if (data.id) {
      url = visualCategory.update(data.id, data)
    } else {
      url = visualCategory.save(data)
    }
    url
      .then((res) => {
        if (res.code == 200 && res.message) {
          Message.success("提交成功")
          formVisible.value = false
          visualCategory.tree().then((res) => {
            depts.value = [{ label: "所有分类", value: 0 }].concat(res.data)
          })
        }
      })
      .catch((e) => {
        console.error(e)
        Message.error("提交失败")
      })
  }
  // 关闭表单提交中状态
  done(false)
}
const formEdit = ({ nodeData }) => {
  form.value = nodeData
  formVisible.value = true
}
const formDel = ({ nodeData }) => {
  visualCategory.realDestroy({ ids: [nodeData.id] }).then((res) => {
    visualCategory.tree().then((res) => {
      depts.value = [{ label: "所有分类", value: 0 }].concat(res.data)
    })
  })
}
</script>
<style scoped lang="less">
:deep(.arco-card-size-small .arco-card-body) {
  padding: 5px;
}
</style>
